package com.common.library.net;

import android.util.Log;

import com.common.library.tools.AppInfo;
import com.common.library.tools.JSONTools;
import com.yolanda.nohttp.Headers;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.download.DownloadRequest;
import com.yolanda.nohttp.rest.Request;

import org.json.JSONObject;

import java.util.HashMap;

/**
 * @title 网络请求
 * 实现网络缓存，其中CancelSign标签作为对请求队列中请求取消操作的依据
 * <p/>
 * 缓存模式：
 * 2. 当请求服务器失败读缓存
 * CacheMode.REQUEST_FAILED_READ_CACHE
 * 3. 仅仅读取缓存，不请求服务器
 * CacheMode.ONLY_READ_CACHE
 * 4. 如果发现有缓存直接成功，没有缓存才请求服务器
 * CacheMode.IF_NONE_CACHE_REQUEST
 */
public class HttpRequest {
    /**
     * 表单请求
     */
    public static Request<JSONObject> newRequestJSONObject(String url, RequestMethod requestMethod, HashMap<String, String> maps, Object sign) {
        Request<JSONObject> request = NoHttp.createJsonObjectRequest(url, requestMethod == null ? RequestMethod.POST : requestMethod);
        request.setCancelSign(sign);
        request.add(maps);
        Log.i("com.txf.prevention.net", "--->UN NoHttp 请求数据：" + "\n" +
                "请求标识 ; " + sign + "\n" +
                "接口根地址 ; " + url + "\n" +
                "请求参数 : " + maps
        );
        return request;
    }

    /**
     * json字符串请求
     */
    public static Request<String> newRequestString(String url, RequestMethod requestMethod, HashMap<String, Object> maps, Object sign) {
        Request<String> request = NoHttp.createStringRequest(url, requestMethod == null ? RequestMethod.POST : requestMethod);
        request.setCancelSign(sign);
        request.setParamsEncoding("utf-8");
        request.setDefineRequestBody(JSONTools.toJson(maps), Headers.HEAD_VALUE_ACCEPT_APPLICATION_JSON);
        Log.i("com.txf.prevention.net", "--->UN NoHttp 请求数据：" + "\n" +
                "请求标识 ; " + sign + "\n" +
                "接口根地址 ; " + url + "\n" +
                "请求参数 ; " + maps
        );
        return request;
    }
    /**
     * 文件下载
     */
    public static DownloadRequest newDownloadRequest(String url, String filename, Object sign) {
        DownloadRequest request = NoHttp.createDownloadRequest(url, RequestMethod.POST, AppInfo.getInstance().getStoragePath(), filename, false, true);
        request.setCancelSign(sign);
        Log.i("com.txf.prevention.net", "--->UN NoHttp 请求数据：" + "\n" +
                "请求标识 ; " + sign + "\n" +
                "下载后的文件路劲 ; " + AppInfo.getInstance().getStoragePath() + "\n" +
                "下载后的文件名 ; " + filename + "\n" +
                "接口根地址 ; " + url
        );
        return request;
    }

}
